package com.tinem.platform.service.message.observable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.enums.message.CommandEnum;
import com.tinem.platform.module.pojo.enums.message.Message;
import com.tinem.platform.module.pojo.enums.message.PushChannel;
import com.tinem.platform.module.starter.jms.enums.TopicEnum;
import com.tinem.platform.module.starter.jms.util.impl.JmsTopicUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className WebSocketListener
 * @description TODO
 * @site
 * @company
 * @create 2021/12/1 17:11:03
 */
@Slf4j
@Service
@Order(100)
public class WebSocketListener implements ApplicationListener<MessageObservable> {

    String name="platform-cloud-web-netty";

    @Resource
    JmsTopicUtil jmsTopicUtil;

    @Override
    public void onApplicationEvent(MessageObservable event) {
        if(!event.getSource().getPushChannel().equals(PushChannel.WEB_SOCKET)){
            return;
        }
        if(!(event.getBody() instanceof Map)){
            return;
        }
        Message message = Message.builder()
                .command(CommandEnum.message)
                .client_msg_id(event.getId())
                .success(true)
                .message("success")
                .send_time(System.currentTimeMillis())
                .req(JSON.parseObject(JSON.toJSONString(event.getBody())))
                .build();
        String body = JSONObject.toJSONString(message);
        switch (event.getSource().getExtWebSocketType()){
            case USER:
                jmsTopicUtil.sendMessage(body,name,TopicEnum.WEB_SOCKET_USER,event.getSource().getTo());
                return;
            case CHAT_ROOM:
                jmsTopicUtil.sendMessage(body,name,TopicEnum.WEB_SOCKET_CHAT_ROOM,event.getSource().getTo());
                return;
            case ALL_USER:
                jmsTopicUtil.sendMessage(body,name,TopicEnum.WEB_SOCKET_ALL_USER);
                return;
            case ALL_SESSION:
                jmsTopicUtil.sendMessage(body,name,TopicEnum.WEB_SOCKET_ALL_SESSION);
                return;
        }
    }
}
